import React, { createContext, useContext, useState, useEffect } from 'react';
import { App } from 'antd';

const AuthContext = createContext();

export const useAuth = () => {
    const context = useContext(AuthContext);
    if (!context) {
        throw new Error('useAuth must be used within AuthProvider');
    }
    return context;
};

export const AuthProvider = ({ children }) => {
    const [user, setUser] = useState(null);
    const [isLoading, setIsLoading] = useState(true);

    // 检查本地存储中的用户信息
    useEffect(() => {
        const checkAuth = () => {
            try {
                const storedUser = localStorage.getItem('user');
                if (storedUser) {
                    const userData = JSON.parse(storedUser);
                    setUser(userData);
                }
            } catch (error) {
                console.error('解析用户数据失败:', error);
                localStorage.removeItem('user');
            } finally {
                setIsLoading(false);
            }
        };

        checkAuth();
    }, []);

    // 登录函数
    const login = (userData, remember = false) => {
        setUser(userData);

        if (remember) {
            // 如果选择记住密码，保存到localStorage
            localStorage.setItem('user', JSON.stringify(userData));
            localStorage.setItem('rememberPassword', 'true');

            // 保存用户名和密码（实际项目中不建议明文保存密码）
            localStorage.setItem('savedUsername', userData.username);
            localStorage.setItem('savedPassword', userData.password || '');
        } else {
            // 不记住密码，只保存用户信息到sessionStorage
            sessionStorage.setItem('user', JSON.stringify(userData));
            localStorage.removeItem('rememberPassword');
            localStorage.removeItem('savedUsername');
            localStorage.removeItem('savedPassword');
        }
    };

    // 登出函数
    const logout = () => {
        setUser(null);

        // 清除会话数据
        localStorage.removeItem('user');
        sessionStorage.removeItem('user');

        // 如果没有选择记住密码，清除所有登录相关数据
        const rememberPassword = localStorage.getItem('rememberPassword');
        if (!rememberPassword) {
            localStorage.removeItem('savedUsername');
            localStorage.removeItem('savedPassword');
        }

        // 注意：这里不能使用 message，因为Context组件不能使用 useApp hook
        // 登出消息将由调用组件处理
    };

    // 检查是否已登录
    const isAuthenticated = !!user;

    // 获取保存的登录信息
    const getSavedCredentials = () => {
        const rememberPassword = localStorage.getItem('rememberPassword');
        if (rememberPassword) {
            return {
                username: localStorage.getItem('savedUsername') || '',
                password: localStorage.getItem('savedPassword') || '',
                remember: true
            };
        }
        return {
            username: '',
            password: '',
            remember: false
        };
    };

    const value = {
        user,
        isLoading,
        isAuthenticated,
        login,
        logout,
        getSavedCredentials
    };

    return (
        <AuthContext.Provider value={value}>
            {children}
        </AuthContext.Provider>
    );
};

export default AuthProvider;
